// const store = {
// 	state: {
// 		cart: [{
// 			goodsId: 495,
// 			num: 99,
// 			checked: true
// 		}]
// 	}
// }

import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		// cart声明时,直接stroage=>vuex
		cart: uni.getStorageSync('cart') || []
	},
	mutations: {
		// 把勾选的商品从vuex去掉
		arrangeCart(state){
			// 更新
			//过滤只保留没有勾选的商品
			state.cart = state.cart.filter(item => {
				return !item.checked
			})
		},
		//购物车更新vuex
		updateCart(state, goodsList) {
			state.cart = goodsList.map(item => {
				return {
					goodsId: item.goodsId,
					checked: item.checked,
					num: item.num
				}
			})
		},
		// 加入购物车
		add2Cart(state, goodsId) {
			let cartArr = state.cart
			//更新
			// this.goodsId = this.goodsDetail.goods_id
			// 在cartArr里面找一个符合条件的对象,条件对象.goodsId和当前需要加入购物车的goodsId相等
			let targetIndex = cartArr.findIndex(item => {
				return item.goodsId === goodsId
			})
			if (targetIndex !== -1) {
				let targetGoods = cartArr[targetIndex]
				// 非首次添加，num++,checked:true
				targetGoods.num = targetGoods.num + 1
				targetGoods.checked = true
				////先删除，再插入头部
				cartArr.splice(targetIndex, 1)
				cartArr.unshift(targetGoods)
			} else {
				// 首次添加
				let newGoods = {
					goodsId: goodsId,
					checked: true,
					num: 1
				}
				// 插入到cartArr的头部
				cartArr.unshift(newGoods)
			}
		}
	},
	plugins: [createLogger()]
})

export default store
